package com.sgg.gulimall_search.service.impl;

import com.alibaba.fastjson.JSON;
import com.sgg.gulimall_common.to.ProductUPTo;

import com.sgg.gulimall_search.service.IProductService;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

@Service
public class ProdectServiceImpl implements IProductService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;


    /**
     * 根据实体类，添加
     *
     * @param productToList
     * @return
     */
    @Override
    public int insertProduct(List<ProductUPTo> productToList) {

        Integer result = 0;


        String jsonString = JSON.toJSONString(productToList);
//        BulkRequest bulkRequest = new BulkRequest();
//        bulkRequest.add(new IndexRequest("posts").id("5").source(jsonString,XContentType.JSON));

        final IndexRequest posts = new IndexRequest("posts").id("5").source(jsonString, XContentType.JSON);
        try {
            restHighLevelClient.index(posts,RequestOptions.DEFAULT);
            result=1;
        } catch (IOException e) {
            e.printStackTrace();
        }

//        try {
////            restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
////            result=1;
//        } catch (IOException e) {
//            e.printStackTrace();
//        }

        return result;
    }
}
